package cn.share.life.module.images.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.share.life.common.exception.ServiceException;
import cn.share.life.module.images.dal.GirlImagesDO;
import cn.share.life.module.images.dal.vo.GirlImagesPageReqVO;
import cn.share.life.module.images.dal.vo.GirlImagesSaveReqVO;
import cn.share.life.module.images.mapper.GirlImagesMapper;
import cn.share.life.module.images.service.GirlImagesService;
import cn.share.life.common.pojo.PageResult;
import cn.share.life.module.images.utils.HtmlFidAndPathEnums;
import cn.share.life.module.images.utils.ImageFileUtils;
import cn.share.life.module.images.utils.JsoupUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 美女图片 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class GirlImagesServiceImpl implements GirlImagesService {
    // 创建线程池，线程数可以根据需要调整
    private final ExecutorService executorService = Executors.newFixedThreadPool(30);

    @Resource
    private GirlImagesMapper girlImagesMapper;

    @Override
    public int initGirlImages(GirlImagesSaveReqVO createReqVO) {

        String basePath = createReqVO.getBasePath();
        if (StringUtils.isBlank(basePath)) {
            throw new ServiceException("基础目录不能为空");
        }
        basePath = basePath.replace("\\", "/");


        List<GirlImagesDO> imagesDOList = Lists.newArrayList();
        List<File> imageFileList = ImageFileUtils.getImageFileList(basePath);
        for (File imageFile : imageFileList) {
            String fileName = FileUtil.mainName(imageFile);
            String path = imageFile.getPath();
            path = path.replace("\\", "/");
            String imagePath = path.substring(basePath.length() + 1); // 去掉基础目录的前缀

//            HtmlFidAndPathEnums enumByBasePath = HtmlFidAndPathEnums.getEnumByBasePath(path);
//            if (enumByBasePath == null) {
//                throw new ServiceException("图片路径不符合规范，无法处理：" + path);
//            }

            imagesDOList.add(GirlImagesDO.builder()
                    .basePath(basePath).fileName(fileName).imagePath(imagePath)
                    .build());
        }

        Boolean insertBatch = girlImagesMapper.insertBatch(imagesDOList, 1000);
        if (!insertBatch) {
            throw new ServiceException("初始化美女图片失败");
        }
        return imagesDOList.size();
    }

    @Override
    public void deleteGirlImages(String id) {
        // 删除
        girlImagesMapper.deleteById(id);
    }

    @Override
    public PageResult<GirlImagesDO> getGirlImagesPage(GirlImagesPageReqVO pageReqVO) {
        return girlImagesMapper.selectPage(pageReqVO);
    }

    @Override
    public int updateGirlImages(String id, String classify) {
        return girlImagesMapper.update(null, Wrappers.lambdaUpdate(GirlImagesDO.class)
                .eq(GirlImagesDO::getId, id)
                .set(GirlImagesDO::getClassify, classify)
        );
    }

    @Override
    public Integer syncWebInfo(String baseUrl) {
        HtmlFidAndPathEnums[] values = HtmlFidAndPathEnums.values();
        for (HtmlFidAndPathEnums enums : values) {
            String webUrl = ImageFileUtils.getWebPageUrl(baseUrl, enums);
            String saveDirectory = enums.getBasePath() + enums.getUrlPath();

            for (int i = 1; i <= enums.getPage(); i++) {
                String pageUrl = webUrl + i;
                System.out.println("正在下载网页,----------第 " + i + " 页-------------" + saveDirectory);

                insertByPath(baseUrl, pageUrl, saveDirectory);
            }
        }
        return 0;
    }

    public void insertByPath(String baseUrl, String pageUrl, String saveDirectory){
        try {
            Document doc = JsoupUtils.getDocument(pageUrl);
            if (doc == null) {
                throw new ServiceException("网页不存在或无法访问: " + pageUrl);
            }
            Elements elements = doc.select("[id^=a_ajax_]");
            for (Element element : elements) {
                executorService.submit(() -> {
                    String href = element.attr("href");
                    if (StringUtils.isNotEmpty(href)) {
                        String url = baseUrl + href;
                        boolean downloaded = downloadAllImagesFromPage(url, saveDirectory);
                        if (!downloaded) {
                            System.out.println("网页已存在,跳过下载: " + url);
                        } else {
                            System.out.println("网页下载完成: " + url);
                        }
                    }
                });
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public static boolean downloadAllImagesFromPage(String pageUrl, String saveDirectory) {
        try {
            Document doc = JsoupUtils.getDocument(pageUrl);
            if (doc == null) {
                throw new ServiceException("网页不存在或无法访问: " + pageUrl);
            }

            String title = getTitleByDoc(doc);
            saveDirectory = saveDirectory + "/" + title;
            if (Files.exists(Paths.get(saveDirectory))) {
                return false;
            } else {
                System.out.println("创建目录-------------------------------------------------------------: " + saveDirectory);
                Files.createDirectories(Paths.get(saveDirectory));
            }

            System.out.println("正在下载网页: " + title);
            Element readTpc = doc.getElementById("read_tpc");

            String txt = saveDirectory + "/content.txt";
            if (readTpc != null) {
                Files.write(Paths.get(txt), readTpc.html().getBytes(StandardCharsets.UTF_8));
            }

            // 获取网页内所有图片的URL
            Elements imgElements = null;
            if (readTpc != null) {
                imgElements = readTpc.select("img[src]");
            }
            String txt2 = saveDirectory + "/url.txt";
            for (Element imgElement : imgElements) {
                String imgUrl = imgElement.absUrl("src");
                FileUtil.appendLines(Collections.singletonList(imgUrl), txt2, StandardCharsets.UTF_8);
            }
            System.out.println("网页内所有图片下载完成！");
        } catch (Exception e) {
            System.out.println("下载网页图片出现错误: " + e.getMessage());
        }
        return true;
    }

    private static String getTitleByDoc(Document doc) {
        String title = doc.title();
        if (StringUtils.isEmpty(title)) {
            title = "default_" + System.currentTimeMillis();
        }

        Element breadCrumb = doc.getElementById("breadCrumb");
        if (breadCrumb != null) {
            Elements font = breadCrumb.select("font");
            if (font != null && font.size() > 0) {
                Element last = font.select("a").last();
                if (last != null) {
                    String html = last.html();
                    if (StringUtils.isNotEmpty(html)) {
                        title = html;
                    }
                }
            }
        }
        return title.replaceAll("/", "_");
    }
}